package com.supply.dl.utils.utils;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.WindowManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * <p>图片处理的工具类</p>
 * <p>2014/11/13</p>
 * @author yangting
 * @version CmgeForum 1.0.0
 */
public class ImageUtils
{

	/**
	 * 将Bitmap数组转换成Drawable对象(资源使用，会根据屏幕密度进行可拉)
	 */
	public static Drawable bitmapToResDrawable(Context context, Bitmap b)
	{
		if (b == null)
			return null;
		BitmapDrawable d = new BitmapDrawable(b);
		if (context != null)
		{
			int density = context.getResources().getDisplayMetrics().densityDpi;
			d.setTargetDensity((int) (density * (density * 1.0f / 240)));
		}
		d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
		return d;
	}

	/**
	 * 将Bitmap数组转换成Drawable对象(资源使用，会根据屏幕密度进行可拉)
	 */
	public static Drawable bitmapToResDrawable(Context context, Bitmap b, int dp)
	{
		if (b == null)
			return null;
		BitmapDrawable d = new BitmapDrawable(b);
		if (context != null)
		{
			int density = context.getResources().getDisplayMetrics().densityDpi;
			d.setTargetDensity((int) (density * (density * 1.0f / dp)));
		}
		d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
		return d;
	}

	/**
	 * 将Bitmap数组转换成Drawable对象(资源使用，会根据屏幕密度进行可拉)
	 */
	public static Drawable bitmapToFaceResDrawable(Context context, Bitmap b)
	{
		if (b == null)
			return null;
		BitmapDrawable d = new BitmapDrawable(b);
		if (context != null)
		{
			int density = context.getResources().getDisplayMetrics().densityDpi;
			d.setTargetDensity((int) (density * (density * 1.0f / 400)));
		}
		d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
		return d;
	}

	/**
	 * 缩放图片
	 * @param bitmap 要缩放的图片
	 * @param w 缩放后的宽度
	 * @param h 缩放后的高度
	 * @return 缩放后的图片
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, float w, float h)
	{
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = (w / width);
		float scaleHeight = (h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
	}

	/**
	 * 缩放图片
	 * @param drawable 要缩放的图片
	 * @param w 缩放后的宽度
	 * @param h 缩放后的高度
	 * @return 缩放后的图片
	 */
	public static Drawable zoomDrawable(Resources resources, Drawable drawable, float w, float h)
	{
		Bitmap bitmap = zoomBitmap(drawableToBitmap(drawable), w, h);
		return bitmapToDrawable(resources, bitmap);
	}

	/**
	 * 画一个圆角图
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap)
	{
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		//		final RectF rectF = new RectF(rect);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		float mDrawableRadius = Math.min(rect.height() / 2, rect.width() / 2);
		canvas.drawCircle(rect.width() / 2, rect.height() / 2, mDrawableRadius, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 将Drawable数组转换成Bitmap对象
	 */
	public static Bitmap drawableToBitmap(Drawable d)
	{
		return d == null ? null : ((BitmapDrawable) d).getBitmap();
	}

	/**
	 * 将Bitmap数组转换成Drawable对象
	 */
	public static Drawable bitmapToDrawable(Resources resources, Bitmap b)
	{
		if (b == null)
			return null;
		return new BitmapDrawable(resources, b);
	}

	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle)
	{
		int i;
		int j;
		if (bmp.getHeight() > bmp.getWidth())
		{
			i = bmp.getWidth();
			j = bmp.getWidth();
		}
		else
		{
			i = bmp.getHeight();
			j = bmp.getHeight();
		}

		Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
		Canvas localCanvas = new Canvas(localBitmap);

		localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
		if (needRecycle && !bmp.isRecycled())
			bmp.recycle();
		ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
		localBitmap.compress(Bitmap.CompressFormat.JPEG, 100, localByteArrayOutputStream);
		localBitmap.recycle();
		byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
		try
		{
			localByteArrayOutputStream.close();
		}
		catch (Exception e)
		{
			// F.out(e);
		}
		return arrayOfByte;
	}

	/**
	 * 压缩图片(压缩图片的质量)
	 * @param image 要压缩的Bitmap
	 * @param compressSize 压缩最大的大小(单位kb)
	 * @return 返回被压缩后的bitmap
	 */
	public static byte[] compressImage(Bitmap image, int compressSize)
	{
		if (image == null)
			return null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		long kb = 1024 * compressSize;
		// 循环判断如果压缩后图片是否大于指定的大小,大于继续压缩
		while (baos.toByteArray().length > kb)
		{
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
			if (options == 0)
				options = 1;
			else if (options < 0)
			{
				break;
			}
		}
		return baos.toByteArray();
	}

	/**
	 * 压缩图片到指定路径
	 */
	public static synchronized boolean compressToPath(Bitmap image, String savePath, int compressSize)
	{
		if (image == null || TextUtils.isEmpty(savePath))
		{
			return false;
		}
		FileUtils.makeFile(savePath);

		ByteArrayInputStream isBm = new ByteArrayInputStream(compressImage(image, compressSize));// 把压缩后的数据baos存放到ByteArrayInputStream中

		return FileUtils.writeFile(savePath, isBm);
	}

	/**
	 * 获取指定的图片地址(本地)得到Bitmap对象
	 * @param path 图片的地址
	 */
	public static Bitmap loadBitmap(Context context, String path)
	{
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		options.inSampleSize = computeSampleSize(options, -1, display.getWidth() * display.getHeight() * 2);
		options.inJustDecodeBounds = false;
		options.inDither = false;
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;

		Bitmap resultBitmap = null;
		while (true)
		{
			try
			{
				resultBitmap = BitmapFactory.decodeFile(path, options);
				break;
			}
			catch (OutOfMemoryError e)
			{
				System.gc();
				if (options.inSampleSize == 8)
				{
					break;
				}
				options.inSampleSize = options.inSampleSize + 1;
			}
		}
		return resultBitmap;
	}

	/*
	 * Compute the sample size as a function of minSideLength and maxNumOfPixels. minSideLength is used to specify that minimal width or height of a bitmap. maxNumOfPixels is used to specify the maximal size in pixels that is tolerable in terms of memory usage. The function returns a sample size based on the constraints. Both size and minSideLength can be passed in as IImage.UNCONSTRAINED, which indicates no care of the corresponding constraint. The functions prefers returning a sample size that generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED. Also, the function rounds up the sample size to a power of 2 or multiple of 8 because BitmapFactory only honors sample size this way. For example, BitmapFactory downsamples an image by 2 even though the request is 3. So we
	 * round up the sample size to avoid OOM.
	 */
	public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels)
	{
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8)
		{
			roundedSize = 1;
			while (roundedSize < initialSize)
			{
				roundedSize <<= 1;
			}
		}
		else
		{
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static final int UNCONSTRAINED = -1;

	private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels)
	{
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound)
		{
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == UNCONSTRAINED) && (minSideLength == UNCONSTRAINED))
		{
			return 1;
		}
		else if (minSideLength == UNCONSTRAINED)
		{
			return lowerBound;
		}
		else
		{
			return upperBound;
		}
	}

	/**
	 * 获取视频的缩略图
	 * 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
	 * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
	 * @param videoPath 视频的路径
	 * @param width 指定输出视频缩略图的宽度
	 * @param height 指定输出视频缩略图的高度度
	 * @param kind 参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
	 *            其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
	 * @return 指定大小的视频缩略图
	 */
	public static Bitmap getVideoThumbnail(String videoPath, int width, int height,
									 int kind) {
		Bitmap bitmap = null;
		File file = new File(videoPath);
		if (!file.exists()) {
			return bitmap;
		}
		// 获取视频的缩略图
		bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	public static String retrievePath(Context context, Intent sourceIntent, Intent dataIntent)
	{
		String picPath = null;
		try
		{
			Uri uri;
			if (dataIntent != null)
			{
				uri = dataIntent.getData();
				if (uri != null)
				{
					picPath = getPath(context, uri);
				}
				if (isFileExists(picPath))
				{
					return picPath;
				}

				//Log.w(TAG, String.format("retrievePath failed from dataIntent:%s, extras:%s", dataIntent, dataIntent.getExtras()));
			}

			if (sourceIntent != null)
			{
				uri = sourceIntent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
				if (uri != null)
				{
					String scheme = uri.getScheme();
					if (scheme != null && scheme.startsWith("file"))
					{
						picPath = uri.getPath();
					}
				}
				if (!TextUtils.isEmpty(picPath))
				{
					File file = new File(picPath);
					if (!file.exists() || !file.isFile())
					{
						//Log.w(TAG, String.format("retrievePath file not found from sourceIntent path:%s", picPath));
					}
				}
			}
			return picPath;
		}
		finally
		{
			//Log.d(TAG, "retrievePath(" + sourceIntent + "," + dataIntent + ") ret: " + picPath);
		}
	}

	@SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri)
	{

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
		{
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri))
			{
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type))
				{
					return String.format("%s/%s", Environment.getExternalStorageDirectory().getPath(), split[1]);
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri))
			{

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri))
			{
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type))
				{
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				}
				else if ("video".equals(type))
				{
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				}
				else if ("audio".equals(type))
				{
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme()))
		{

			// Return the remote address
			if (isGooglePhotosUri(uri))
			{
				return uri.getLastPathSegment();
			}

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme()))
		{
			return uri.getPath();
		}

		return null;
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri)
	{
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri)
	{
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @param selection (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
	{

		Cursor cursor = null;

		try
		{
			cursor = context.getContentResolver().query(uri, new String[] { MediaStore.Images.Media.DATA }, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst())
			{
				final int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				return cursor.getString(index);
			}
		}
		finally
		{
			if (cursor != null)
			{
				cursor.close();
			}
		}
		return null;
	}

	private static boolean isFileExists(String path)
	{
		if (TextUtils.isEmpty(path))
		{
			return false;
		}
		File f = new File(path);
		if (!f.exists())
		{
			return false;
		}
		return true;
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri)
	{
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri)
	{
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	public static Intent choosePicture()
	{
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		return Intent.createChooser(intent, null);
	}

	public static Intent takeBigPicture()
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		//intent.putExtra(MediaStore.EXTRA_OUTPUT, newPictureUri(getNewPhotoPath()));
		return intent;
	}

}
